<?php
class Jerarquia{
	var $m;
	var $arbol;
	var $histo;
	var $actual;
	
	function insertar($matriz,$id,$parent,$orden){
		foreach($matriz as $k=>$v){
			$this->m[$v[$id]] = array(
									'P' => $v[$parent],
									'I' => $v[$id],
									'S' => $v[$orden]
								);// Id, Parent, Sort
		}
	}
	
	function crear_arbol(){
		asort ($this->m);# Ordenamos por padre
		$this->histo=array();
		$this->actual=array();
		foreach($this->m as $k=>$v){
			if($v['P']==0){
				krsort($v);
				$this->arbol[$k]['V']=$v;
				$this->arbol[$k]['H']=array();
				$this->histo[$k]="\$this->arbol[$k]";
				$this->actual[$k]=$k;
				unset($this->m[$k]);
			}
		}
		
	}
	
	private function org_arbol(){
		$actual=$this->actual;
		$this->actual=array();
		foreach($actual as $v){
			eval("\$padre = ".$this->histo[$v]."['V']['I'];");
			#Busca a su hijo segun el ID del padre
			$this->buscar($padre,'P');
		}
	}
	
	function generar_niveles(){
		while(count($this->m)){
			$this->org_arbol();
		}
	}
	
	private function buscar($num,$q){
		
		foreach($this->m as $k=>$v){
			if($v[$q]==$num){
				if($q=='P'){
					krsort($v);
					$this->histo[$k] = $this->histo[$num]."['H'][$k]";
					eval ($this->histo[$k]."['V'] = \$v;");
					eval ($this->histo[$k]."['H'] = array();");
					$this->actual[$k]=$k;
					unset($this->m[$k]);
				}
			}
		}
	}
	
	function ordenar(){
		asort($this->arbol);
		foreach($this->histo as $v){
			eval("if(!empty(".$v."['H'])){
				asort(".$v."['H']);
			}");
		}
	}
	
	function indata(){
		$gets = func_get_args();
		$matriz=$gets[0];
		array_shift($gets);
		$id=$gets[0];
		array_shift($gets);
		foreach($matriz as $k=>$v) $m[$v[$id]]=$v;
			#print_r($m);
		foreach($gets as $vP){
			foreach($this->histo as $k=>$v){
				eval($v."['$vP'] = \$m[$k]['$vP'];");
			}
		}
	}
	
	function es_hijo($padre,$hijo){
		if(strpos(str_replace("['H']",'',$this->histo[$hijo]),"[$padre]")){
			return true;
		}else{
			return false;
		}
	}
	
	function a_cadena(){
		return serialize($this->arbol);
	}
}

